package cn.kgc.day05.listeners;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @author 课工场
 * @date 2024/10/18
 * @description  该类的实例用户监听session会话对象的创建和销毁
 *  会话对象创建
 *  会话对象销毁
 */
@WebListener
public class CustomerSessionListener implements HttpSessionListener {


    // session会话对象创建时自动调用
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("-------sessionCreated---------");
        //  添加一个活跃用户  activeUser  application
        ServletContext servletContext = se.getSession().getServletContext();
        Integer activeUser = (Integer) servletContext.getAttribute("activeUser");
        activeUser++;
        servletContext.setAttribute("activeUser",activeUser);
    }

    // session会话对象销毁时自动调用
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("-------sessionDestroyed---------");
        // 减少一个活跃用户  activeUser   application
        ServletContext servletContext = se.getSession().getServletContext();
        Integer activeUser = (Integer) servletContext.getAttribute("activeUser");
        activeUser--;
        servletContext.setAttribute("activeUser",activeUser);
    }
}
